package com.lazyframework.generator.core;

import com.lazyframework.commons.support.exception.BusinessException;
import com.lazyframework.generator.model.Table;
import com.lazyframework.generator.response.GenerateResponseStatus;
import com.lazyframework.generator.service.SchemaService;

import java.util.List;

public class GenerateManagerImpl implements GenerateManager {

    private final SchemaService schemaService;

    private final List<GenerateProvider> providers;

    public GenerateManagerImpl(SchemaService schemaService, List<GenerateProvider> providers) {
        this.providers = providers;
        this.schemaService = schemaService;
    }

    /**
     * 调用具体Provider生成代码
     *
     * @param metadata 生成代码所需的元数据
     */
    public void generate(GenerateMetadata metadata) {
        String tables = metadata.getTables();
        if (tables == null || "".equals(tables)) {
            return;
        }
        String module = metadata.getModule();   // 模块名
        String basePackage = metadata.getBasePackage(); // 包名
        String projectName = metadata.getProjectName(); // 项目名

        // 获取Provider
        GenerateProvider provider = getProvider(metadata.getFramework());
        if (provider == null) {
            throw new BusinessException(GenerateResponseStatus.NO_PROVIDERS_EXCEPTION);
        }

        String[] tablesAry = tables.split(",");
        for (String s : tablesAry) {
            Table tableInfo = schemaService.getTableInfo(s, metadata.getSchema());
            String domainObjectName = getDomainObjName(s, metadata.isRemoveTablePrefix());
            provider.generate(tableInfo, projectName, basePackage, module, domainObjectName);
        }
    }

    /**
     * 根据传入的框架获取对应的Provider
     *
     * @param framework 框架
     * @return
     */
    private GenerateProvider getProvider(String framework) {
        for (GenerateProvider provider : providers) {
            if (provider.supports(framework)) {
                return provider;
            }
        }
        return null;
    }

    /**
     * 根据表名获取对象名
     *
     * @param tableName         表名
     * @param removeTablePrefix 是否移除表前缀
     * @return 对象名
     */
    private String getDomainObjName(String tableName, boolean removeTablePrefix) {
        if (!tableName.contains("_")) {
            return tableName.substring(0, 1).toUpperCase() + tableName.substring(1).toLowerCase();
        }
        String[] ary = tableName.split("_");
        StringBuilder domainObjName = new StringBuilder();
        for (int i = removeTablePrefix ? 1 : 0; i < ary.length; i++) {
            String c = ary[i];
            domainObjName.append(c.substring(0, 1).toUpperCase()).append(c.substring(1).toLowerCase());
        }
        return domainObjName.toString();
    }

}
